//
//  MHComicDetailViewController.m
//  ManHua
//
//  Created by 赵永泉 on 15/10/26.
//  Copyright © 2015年 蓝欧科技. All rights reserved.
//

#import "MHComicDetailViewController.h"
#import "MHEpisodeNumberCell.h"
#import "MHComicPictureViewController.h"
#import "MHComicEpisode.h"
#import "MHComicDetailHeader.h"
#import "MHAuthorListViewController.h"
#import <AFNetworking.h>
#import "MHComicCommentViewController.h"
#import "MHDataManager.h"

#define kComicDetailSite @"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx"

@interface MHComicDetailViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSDictionary *paramDict;
@property (nonatomic, strong) NSMutableArray *episodeArray;
@property (nonatomic, strong) MHComicDetailHeader *headerView;
@property (nonatomic, assign) NSInteger commentNumber;
@property (nonatomic, assign) BOOL isCollection;

@end

@implementation MHComicDetailViewController

- (void)setComicIntroduct:(MHComicIntroduct *)comicIntroduct
{
    _comicIntroduct = comicIntroduct;
    if (comicIntroduct.BookLinkURL == nil) {
        [self acquirIntroductData];
    }
    if (comicIntroduct.BookState == 0) {
        return;
    }
    else
    {
        self.paramDict = [NSDictionary dictionaryWithObjects:@[[NSNumber numberWithInteger:comicIntroduct.BookID], @"sectionlist"] forKeys:@[@"bookid", @"method"]];
        [self acquirData];
        [self acquirecommentNumberData];

    }
    
    if ([[MHDataManager shareManager]ComicIntroductHasInReadList:comicIntroduct]) {
        _comicIntroduct = [[MHDataManager shareManager]getComicIntroductWithBookID:comicIntroduct.BookID];
    }
    if ([[MHDataManager shareManager]ComicIntroductHasInCollectionList:comicIntroduct]) {
        self.isCollection = YES;
    }

}

-(void)acquirecommentNumberData
{
    NSMutableDictionary *parDict=[NSMutableDictionary dictionary];
    parDict[@"method"]=@"commentcount";
    parDict[@"bookid"]=@"19185";
    
    NSString *pathString=[NSString stringWithFormat:@"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx?method=commentcount&bookid=%ld",self.comicIntroduct.BookID];
    NSURLRequest *requset = [NSURLRequest requestWithURL:[NSURL URLWithString: pathString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//        NSLog(@"%@", data);
//        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding] );
        NSString *commentNum=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        self.commentNumber=[commentNum integerValue];
    }];
}

- (void)acquirIntroductData
{
    NSLog(@"%ld", (long)self.comicIntroduct.BookID);
    [[AFHTTPRequestOperationManager manager] GET:[NSString stringWithFormat:@"https://bone.comikon.net/v8.3/comics/%ld/resources/", (long)self.comicIntroduct.BookID] parameters:[NSDictionary dictionaryWithObjects:@[@"json"] forKeys:@[@"format"]] success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [self.comicIntroduct setValuesForKeysWithDictionary:responseObject];
        [self acquirKonData];
        self.headerView.comicIntroduct = self.comicIntroduct;
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
}

- (void)acquirKonData
{
    [[AFHTTPRequestOperationManager manager] GET:[NSString stringWithFormat:@"https://bone.comikon.net/v8.3/resources/%ld/episodes/", self.comicIntroduct.resource_id] parameters:[NSDictionary dictionaryWithObjects:@[@"json"] forKeys:@[@"format"]] success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        self.episodeArray = [NSMutableArray array];
        for (NSDictionary *dict in responseObject) {
            MHComicEpisode *episode = [MHComicEpisode modelWithDict:dict];
            episode.resource_id = self.comicIntroduct.resource_id;
            [self.episodeArray addObject:episode];
        }
        self.episodeArray = (NSMutableArray *)[[self.episodeArray reverseObjectEnumerator] allObjects];
        [self.collectionView reloadData];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
}

- (void)acquirData
{
    [[AFHTTPRequestOperationManager manager] GET:kComicDetailSite parameters:self.paramDict success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        self.episodeArray = [NSMutableArray array];
        for (NSDictionary *dict in responseObject) {
            MHComicEpisode *episode = [MHComicEpisode modelWithDict:dict];
            [self.episodeArray addObject:episode];
        }
        [self.collectionView reloadData];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor magentaColor];
    
    // 添加一个评论按钮
    UIButton *commentButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 30)];
    [commentButton setTitle:@"评论" forState:UIControlStateNormal];
    [commentButton setTitleColor:kThemeColor forState:UIControlStateNormal];
    commentButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [commentButton addTarget:self action:@selector(didGotoCommentVC) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *commentBtn = [[UIBarButtonItem alloc]initWithCustomView:commentButton];
    self.navigationItem.rightBarButtonItem = commentBtn;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    NSInteger row = 4;
    CGFloat margin = 20;
    CGFloat padding = 10;
    CGFloat itemW = (Width - 2 * margin - (row - 1) * padding) / 3;
    CGFloat itemH = 30;
    flowLayout.itemSize = CGSizeMake(itemW, itemH);
    flowLayout.sectionInset = UIEdgeInsetsMake(margin, margin, margin, margin);
    flowLayout.headerReferenceSize = CGSizeMake(Width, 500);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"MHEpisodeNumberCell" bundle:nil] forCellWithReuseIdentifier:@"EpisodeNumber"];
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"ComicDetailHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ComicDetailHeaderView"];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.comicIntroduct.readSection != nil) {
        [self.headerView.readBurron setTitle:@"继续阅读" forState:UIControlStateNormal];
    }
}

// 评论按钮点击事件
- (void)didGotoCommentVC
{
    MHComicCommentViewController *commentVC = [[MHComicCommentViewController alloc]init];
    commentVC.bookid = [NSString stringWithFormat:@"%ld",(long)self.comicIntroduct.BookID];
    commentVC.commentCount=self.commentNumber;

    self.hidesBottomBarWhenPushed = YES; // 隐藏tarbar
    [self.navigationController pushViewController:commentVC animated:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.episodeArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MHEpisodeNumberCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EpisodeNumber" forIndexPath:indexPath];
    cell.episodeNumber.text = [self.episodeArray[indexPath.row] SectionName];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MHComicPictureViewController *comicPictureVC = [[MHComicPictureViewController alloc]init];
    comicPictureVC.index = indexPath.row;
    comicPictureVC.episodeArray = self.episodeArray;
    comicPictureVC.comicIntroduct = self.comicIntroduct;
    [self presentViewController:comicPictureVC animated:YES completion:nil];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        MHComicDetailHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ComicDetailHeaderView" forIndexPath:indexPath];
        self.headerView = header;
        
        __weak MHComicDetailViewController *test = self;
        header.changeHeaderHeightBlock = ^(CGFloat headerHeight)
        {
            [UIView animateWithDuration:0.25 animations:^{
                ((UICollectionViewFlowLayout *)collectionView.collectionViewLayout).headerReferenceSize = CGSizeMake(Width, headerHeight);
            }];
        };
        header.pushToAutherBlock = ^()
        {
            MHAuthorListViewController *authorVC = [[MHAuthorListViewController alloc]init];
            authorVC.bookAuthor = test.comicIntroduct.BookAuthor;
            authorVC.bookId = test.comicIntroduct.BookID;
            [test.navigationController pushViewController:authorVC animated:YES];
        };
        header.readComicBlock = ^(NSInteger readSectionIndex, NSInteger readPage)
        {
            MHComicPictureViewController *pictureVC = [[MHComicPictureViewController alloc]init];
            pictureVC.index = readSectionIndex;
            pictureVC.episodeArray = test.episodeArray;
            pictureVC.comicIntroduct = self.comicIntroduct;
            [self presentViewController:pictureVC animated:YES completion:nil];
        };
        header.comicIntroduct = self.comicIntroduct;
        if (self.isCollection == YES) {
            [self.headerView.collectionButton setTitle:@"已收藏" forState:UIControlStateNormal];
        }
        
        return header;
    }
    return nil;
}

@end
